package org.kmp.project.util

import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.compositionLocalOf
import com.dokar.sonner.Toaster
import com.dokar.sonner.ToasterState
import com.dokar.sonner.rememberToasterState
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

private val LocalToaster = compositionLocalOf<ToasterState> {
    error("请先在根组件中添加 ToasterProvider")
}

private var GlobalToaster: ToasterState? = null

@Composable
fun ToasterProvider(content: @Composable () -> Unit) {
    val toaster = rememberToasterState()
    Toaster(state = toaster)
    LaunchedEffect(Unit) {
        GlobalToaster = toaster
    }
    CompositionLocalProvider(LocalToaster provides toaster) {
        content()
    }
}


fun showToast(message: String) {
    // 主线程执行，避免Compose UI线程问题
    MainScope().launch {
        GlobalToaster?.show(message,0) ?: run {
            error("Toaster未初始化！请确保根组件包裹了ToasterProvider")
        }
    }
}

